package com.hjd.shop.mq;

import com.alibaba.fastjson.JSON;
import com.hjd.shop.api.service.SOrderService;
import com.hjd.shop.constant.PayState;
import com.hjd.shop.constant.ShopCode;
import com.hjd.shop.constant.SystemUser;
import com.hjd.shop.entity.SOrder;
import com.hjd.shop.entity.SOrderPay;
import com.hjd.shop.mapper.SOrderMapper;
import com.hjd.shop.mapper.SOrderPayMapper;
import com.hjd.shop.pojo.MqEntity;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.MessageModel;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.UnsupportedEncodingException;
import java.util.Date;

/**
 * @Author: hjd
 * @Date: 2020/10/28 0028 22:00
 * @Des: rockmq订单支付监听类
 */
@Component
@RocketMQMessageListener(topic = "${mq.pay.topic}",consumerGroup = "${mq.pay.consumer.group-name}",
        messageModel = MessageModel.BROADCASTING)
@Slf4j
public class OrderPayMqListener implements RocketMQListener<MessageExt> {
    @Autowired
    private SOrderMapper orderMapper;
    @Override
    public void onMessage(MessageExt message) {
        //1.解析消息内容
        try {
            log.info("订单支付|消息:"+message.getMsgId()+"接收成功!");
            String body = new String(message.getBody(), "UTF-8");
            //2.查询订单信息
            SOrderPay orderPay = JSON.parseObject(body, SOrderPay.class);
            SOrder order = orderMapper.selectById(orderPay.getOrderId());
            //3.更改订单状态为已支付
            log.info("开始更改订单:"+order.getOrderId()+"支付状态为已支付!");
            order.setPayStatus(PayState.ORDER_PAYED.getCode())
                    .setModifyTime(new Date())
                    .setModifyUser(SystemUser.SYSTEM_USER);
            //4.更新订单状态到数据库
            orderMapper.updateById(order);
            log.info("更改成功!");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }
}
